<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/13/0013
 * Time: 9:16
 */

namespace app\sports_admin\controller;


use app\exception\SuggestionTypeException;
use think\Request;
use app\sports_admin\model\SuggestionType as SuggestionTypeModel;
use app\sports_admin\service\SuggestionType as SuggestionTypeService;
class SuggestionType extends Base
{
    //信息分类首页
    public function index()
    {
        $cateres = SuggestionTypeModel::getTypeList();
        return view('index',compact('cateres'));
    }
    //添加父级分类页面
    public function addPage()
    {
        return view("parent");
    }
    //添加父级分类
    public function addParentType(Request $request)
    {
        if($request->isAjax()){
            $data = Request::instance()->only(['title']);
            $is_null = SuggestionTypeModel::where('title',$data['title'])->find();
            if(!$is_null){
                $data = SuggestionTypeService::addParentType();
                if(!$data){
                    throw new SuggestionTypeException(['msg' => '添加失败', 'code' => 202]);
                }
                return json(['code'=>200,'msg'=>'添加成功']);
            }else{
                throw new SuggestionTypeException(['msg' => '已经存在的类型名', 'code' => 202]);
            }


        }
    }
    /**
     * 添加子类
    */
    public function add()
    {
        $params = Request::instance()->only(['pid','path','title']);
        return view('add',compact('params'));
    }
    /**
     * 类别添加
    */
    public function typeInsert(Request $request)
    {
        if($request->isAjax()){
            return SuggestionTypeService::typeInsert();
        }
    }
    /**
     * 编辑页面
     * @param $id 类别id
    */
    public function edit(Request $request)
    {
        $id = intval($request->get('id'));
        $info = SuggestionTypeModel::where('id',$id)->find();
        return view('edit',compact('info'));
    }
    /**
     * 类别修改
    */
    public function typeUpdate(Request $request)
    {
        if($request->isAjax()){
            return SuggestionTypeService::typeUpdate();
        }
    }
    /**
     * 类别删除
     * @param $id 类别信息id
    */
    public function typeDelete(Request $request)
    {
        if($request->isAjax()){
            $id = intval($request->post('id'));
            $childType = SuggestionTypeModel::getTypeChild($id);
            if($childType){
                throw new SuggestionTypeException([
                    'msg' => '不能删除含有子类的类别',
                    'code' => 202]);
            }
            $bool = SuggestionTypeModel::destroy($id);
            if(!$bool){
                throw new SuggestionTypeException([
                    'msg' => '删除失败',
                    'code' => 202]);
            }
            return json(['code'=>200,'msg'=>'删除成功']);
        }
    }
}